/**
 * User: daven
 * Date: 14-5-26
 * 款总额为A，银行月利率为β，总期数为m（个月），月还款额设为X
 * 公式：X = Aβ(1+β)^m /[(1+β)^m-1]
 * 等额本息还贷第n个月还贷利息：
 　　X=BX-B= a*i(1+i)^N/[(1+i)^N-1]- a*i(1+i)^(n-1)/[(1+i)^N-1]
 　　（注：BX=等额本息还贷每月所还本金和利息总额，
 　　B=等额本息还贷每月所还本金，
 　　a=贷款总金额
 　　i=贷款月利率，
 　　N=还贷总月数，
 　　n=第n期还贷数
 　　X=等额本息还贷每月所还的利息）

 *等额本金：
 每月应还本金：a/n
 　　每月应还利息：an*i/30*dn
 　　注：a贷款本金 i贷款月利率 n贷款月数 an第n个月贷款剩余本金，a1=a,a2=a-a/n,a3=2-2*a/n...以次类推 dn 第n个月的实际天数，如平年2月就为28，3月就为31，4月就为30，以次类推
 */
define(function(require,exports,module){
    var SERSION = "1.0",
        jquery = $ = require("jquery-1.8.2.min.js");

    function repayInterest(a,r,m){
        return (a*r*Math.pow(1+r,m)/(Math.pow(1+r,m)-1));
    }

    function interest(a, r, m, i) {
        if (arguments.length !== 4) {
            throw new Error('Arguments expected 4.');
        }
        if (!((i > 0) && (i <= m))) {
            throw new Error('times of repay must be greater than 0.');
        }
        return a * r * Math.pow(1 + r, m) / (Math.pow(1 + r, m) - 1) - a * r * Math.pow(1 + r, i - 1) / (Math.pow(1 + r, m) - 1);
    }
    function eqPrinInter(ra, r) {
        return (ra * r);
    }

    function calculator(element){
        this.$elem = $(element);
        this.bindEvent()
    }
    calculator.prototype = {
        bindEvent:function(){
            var that = this;
            this.$elem.find("#interCalc").bind("click",function(){
                that.valid();
            })
        },
        valid:function(){
            this.loanSum = parseFloat(this.$elem.find("#loanSum").val());
            this.yearRate = parseFloat(this.$elem.find("#yearRate").val());
            this.limitTime = parseFloat(this.$elem.find("#limitTime").val());
            this.prize = parseFloat(this.$elem.find("#prize").val());
            this.repayType = parseFloat(this.$elem.find("#repayType").val());
            this.fee = parseFloat(this.$elem.find("#fee").val()/100);
            //todo 验证输入的有效性
            this.loanCalc();
        },
        loanCalc:function(){
            var monthInterest,totalYearRate,flYearRate,dayInterest;
            var loanSum = this.loanSum,
                monthRate = this.monthRate,
                limitTime = this.limitTime,
                prize = this.prize,
                yearRate = this.yearRate,
                fee = this.fee,
                repayType = this.repayType;

            this.monthRate = parseFloat(this.yearRate/100/12);
            this.dayRate = parseFloat(this.yearRate/100/360);

            if(this.repayType === 1){
                //等额本息月还款金额
                monthInterest = repayInterest(loanSum,monthRate,limitTime);
                //年收益率
                //年化利率
                totalYearRate = 24.00 * prize / (limitTime + 1) + yearRate*(1 - fee);
                flYearRate = (Math.pow((1 + totalYearRate/(12*100)),12) - 1) * 100;
                this.render(repayType,loanSum,monthRate,limitTime,monthInterest,fee,prize,totalYearRate,flYearRate);
            }else if(repayType === 2){
                monthInterest = eqPrinInter(loanSum, monthRate);
                //todo 这里的年化利率是加上了投标奖励的金额    实际的年利率*时间 + 投标奖励（月利率*12月=投标奖励的年利率）/ 时间
                totalYearRate = (yearRate*(1-fee) * limitTime + 12 * prize) / limitTime;
                flYearRate = (Math.pow((1 + totalYearRate / (12*100) * limitTime), 12 / limitTime) - 1) * 100;
                this.render(repayType,loanSum,monthRate,limitTime,monthInterest,fee,prize,totalYearRate,flYearRate);
            }else if(repayType === 3){
                dayInterest = eqPrinInter(loanSum, this.dayRate);

                totalYearRate = yearRate + prize / limitTime * 360;
                flYearRate = (Math.pow((1 + totalYearRate / 36500 * limitTime), 365 / limitTime) - 1) * 100;

                this.render(repayType,loanSum,this.dayRate,limitTime,dayInterest,fee,prize,totalYearRate,flYearRate);
            }
        },
        render:function(repayType,loanSum,monthRate,limitTime,monthRepay,fee,prize,totalYearRate,flYearRate){
            var tmpl = ['<table class="table"><thead><tr><th>期数</th><th>应收本金</th><th>应收利息</th><th>管理费</th><th>实际回款总额</th><th>剩余回款</th></tr></thead><tbody>','</tbody></table>'],
                html_tmpl = '';
            var balance = loanSum;
            var interestSum = 0,
                feeSum = 0,
                realSum = 0,
                prizeSum = 0;
            var getInterest = $.noop;

            if(repayType === 1){
                getInterest = interest
            }else if(repayType === 2 || repayType === 3){
                getInterest = eqPrinInter
            }

            for(var i = 1;i<(limitTime+1);i++){
                var interestMonth = getInterest(loanSum,monthRate,limitTime,i),
                    feeMonth = interestMonth*fee,
                    realMonth = monthRepay-feeMonth;

                balance = balance - monthRepay + interestMonth;

                if(repayType === 2||repayType ===3 && i === limitTime){
                    realSum += loanSum;
                    html_tmpl+='<tr><td>'+i+'</td><td>'+(loanSum+monthRepay-interestMonth).toFixed(2)+'</td>' +
                        '<td>'+interestMonth.toFixed(2)+'</td><td>'+ (-feeMonth).toFixed(2)+'</td><td>'+(loanSum+realMonth).toFixed(2)+'</td><td>0.00</td></tr>'
                }else{
                    html_tmpl+='<tr><td>'+i+'</td><td>'+(monthRepay-interestMonth).toFixed(2)+'</td>' +
                        '<td>'+interestMonth.toFixed(2)+'</td><td>'+ (-feeMonth).toFixed(2)+'</td><td>'+realMonth.toFixed(2)+'</td><td>'+Math.abs(balance).toFixed(2)+'</td></tr>'
                }

                interestSum += interestMonth;
                feeSum +=feeMonth;
                realSum+=realMonth;
            }
            prizeSum = Math.round(loanSum*prize/100);

            html_tmpl +='<tr><td>总计</td><td>'+loanSum.toFixed(2)+'</td>' +
                '<td>'+interestSum.toFixed(2)+'</td><td>'+ (-feeSum).toFixed(2)+'</td><td>'+realSum.toFixed(2)+'</td><td>--</td></tr>'
            tmpl = tmpl[0]+html_tmpl+tmpl[1];

            $('.restream_table').html(tmpl);
            $(".totalYearRate").html((Math.round(totalYearRate*100)/100).toFixed(2));
            $(".monthRate").html((Math.round(totalYearRate/12*100)/100).toFixed(2));
            $(".flYearRate").html((Math.round(flYearRate*100)/100).toFixed(2));
            $(".flMonthRate").html((Math.round(flYearRate/12*100)/100).toFixed(2));

            $(".sum").html((interestSum+prizeSum).toFixed(2));
            $(".interest").html(interestSum.toFixed(2));
            $(".reward").html(prizeSum.toFixed(2));
        }
    };
    return calculator;
});

